<template>
    <div id="add-edit-active">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="120px" :rules="rules">
                <el-row>
                    <template v-if="currentType === 0">
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="设备类型" prop="l_MachineTypeId">
                                <el-select 
                                    class="m-2" 
                                    filterable
                                    placeholder="请选择设备类型" 
                                    v-model="ruleForm.l_MachineTypeId" 
                                    @change="equTypeChange"
                                >
                                    <el-option
                                        v-for="item in equTypeOption"
                                        :key="item.n_Id"
                                        :label="item.v_Name"
                                        :value="item.n_Id"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="设备" prop="v_Names">
                                <el-select 
                                    class="m-2" 
                                    placeholder="请选择设备" 
                                    filterable
                                    v-model="ruleForm.v_Names" 
                                    @change="equChange"
                                >
                                    <el-option
                                        v-for="item in equOption"
                                        :key="item.n_Id"
                                        :label="item.v_Name"
                                        :value="item.n_Id"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </template>
                    <template v-if="currentType === 1">
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="作业活动名称" prop="v_Name">
                                <el-input v-model="ruleForm.v_Name" placeholder="请输入作业活动名称" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="作业类别" prop="v_Kind">
                                <el-select 
                                    filterable
                                    class="m-2" 
                                    placeholder="请选择作业类别" 
                                    v-model="ruleForm.v_Kind" 
                                >
                                    <el-option
                                        v-for="item in typeOption"
                                        :key="item.id"
                                        :label="item.value"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="作业频率">
                                <el-select 
                                    filterable
                                    class="m-2" 
                                    placeholder="请选择作业频率" 
                                    v-model="ruleForm.v_FrequencyName" 
                                    @change="genreChange"
                                    value-key="value"
                                >
                                    <el-option
                                        v-for="item in genreOption"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="岗位" prop="v_PostName">
                                <el-select 
                                    filterable
                                    class="m-2" 
                                    placeholder="请选择岗位" 
                                    v-model="ruleForm.v_PostName" 
                                    @change="postChange"
                                    value-key="id"
                                >
                                    <el-option
                                        v-for="item in postOption"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                            <el-form-item label="备注">
                                <el-input type="textarea" v-model="ruleForm.v_Remark" placeholder="请输入备注" clearable />
                            </el-form-item>
                        </el-col>
                    </template>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button type="primary" :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRefs , toRaw , watch } from 'vue';
import { FormInstance, FormRules, ElButton, ElCol, ElDialog, ElForm, ElRow } from 'element-plus';
import { 
    sysDictDataList , 
    SMSDCAnalysisUnitJobAdd , 
    SMSDCAnalysisUnitJobUpdate , 
    SMSDCAnalysisUnitMachineAdd , 
    SMSDCAnalysisUnitMachineUpdate ,
    ClassifyGetList,
    EquipmentGetList,
} from '/@/api/centerControl/sms';
import { sysPosList } from '/@/api/centerControl/pubilc';
import axios from 'axios';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    v_Name: String, // 作业活动名称
    v_Kind: String, // 作业类别
    n_Frequency: Number, // 作业频率
    v_FrequencyName: String, // 作业频率名称
    l_PostId: Number, // 岗位Id
    v_PostName: String, // 岗位名称
    v_Remark: String, // 备注

    v_Names: String, // 设备名称
    l_MachineTypeId: any, // 设备类型id
    l_MachineId: any, // 设备id
}
export default defineComponent( {
    name: 'add-edit-active',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        },
        rowInfo: {
            type: String,
            default: ''
        },
        currentStatus: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref();
        const ruleFormRef = ref();
        const postOption = ref();
        const typeOption = ref();
        const currentType = ref();
        const equTypeOption = ref();
        const equOption = ref();

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 作业活动名称
            v_Name: [
				{ required: true, message: '请输入作业活动名称', trigger: 'blur' },
			],
            // 作业类别
            v_Kind: [
				{ required: true, message: '请选择作业活动名称', trigger: 'change' },
			],
            // 作业频率名称
            v_FrequencyName: [
                { required: true, message: '请选择作业频率', trigger: 'change' },
            ],
            // 岗位
            v_PostName: [
                { required: true, message: '请选择岗位', trigger: 'change' },
            ],

            
            // 设备类型id
            l_MachineTypeId: [
                { required: true, message: '请选择设备类型', trigger: 'change' },
            ],
            // 设备名称
            v_Names: [
                { required: true, message: '请选择设备', trigger: 'change' },
            ],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick();
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelActiveClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    let param: any = toRaw(state.ruleForm);
                    state.repeatDis = true;
                    if(props.currentStatus === 'add'){
                        param.l_AnalysisUnitId = JSON.parse(props.rowInfo).id;
                        try{
                            let res:any;
                            if(JSON.parse(props.rowInfo).n_Type === 0){
                                res = await SMSDCAnalysisUnitMachineAdd(param);
                            }
                            if(JSON.parse(props.rowInfo).n_Type === 1){
                                res = await SMSDCAnalysisUnitJobAdd(param);
                            }
                            if(res.success){
                                state.repeatDis = false;
                                ctx.emit('updateData');
                                ctx.emit('controlActiveClick');
                            }else{
                                state.repeatDis = false;
                            }
                        }catch(error){state.repeatDis = false;}
                    }else{
                        let res:any;
                        try{
                            if(JSON.parse(props.rowInfo).n_Type === 1) res = await SMSDCAnalysisUnitJobUpdate(param);
                            if(res.success){
                                state.repeatDis = false;
                                ctx.emit('updateData');
                                ctx.emit('controlActiveClick');
                            }else{
                                state.repeatDis = false;
                            }
                        }catch(error){ state.repeatDis = false; }
                    }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /*** getDictFun 获取类型字典值 */
        const getDictFun = async() => {
            let param: any = {};
            param.TypeCode = 'KindType';
            let res: any = await sysDictDataList(param);
            if(res.success) typeOption.value = res.data;

            let params:any = {};
            let ras: any = await sysPosList(params);
            if(ras.success) postOption.value = ras.data;
        }
        /*** postChange 职位改变事件 */
        const postChange = (val: any) => {
            console.log(val,'val')
            state.ruleForm.l_PostId = val.id;
            state.ruleForm.v_PostName = val.name;
        }

        /*** genreChange 作业频率选择事件 */
        const genreChange = (val: any) => {
            console.log(val,'val')
            state.ruleForm.n_Frequency = val.value;
            state.ruleForm.v_FrequencyName = val.label;
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                if(props.rowInfo !== ''){
                    let item = JSON.parse(props.rowInfo);
                    currentType.value = item.n_Type;
                    if(item.n_Type === 0) facilityTypeFun(); // 设备类型数据
                    else getDictFun(); // 作业类接口
                }
                if(props.currentStatus === 'edit'){
                    titleCon.value = '编辑';
                    console.log(JSON.parse(props.repairInfo),'repairInfo')
                    state.ruleForm = JSON.parse(props.repairInfo);
                }else{
                    titleCon.value = '新增'
                    state.ruleForm = {
                        v_Name: '', // 作业活动名称
                        v_Kind: '', // 作业类别
                        n_Frequency: 0, // 作业频率
                        v_FrequencyName: '', // 作业频率名称
                        l_PostId: 0, // 岗位Id
                        v_PostName: '', // 岗位名称
                        v_Remark: '', // 备注

                        v_Names: '', //设备名称
                        l_MachineTypeId: '', // 设备类型id
                        l_MachineId: '', // 设备id
                    }
                }
            }
        })

        /*** 设备改变事件 */
        const equChange = (val: any) => {
            console.log(val,'val')
            state.ruleForm.l_MachineId = val;
        }

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })
        
        /*** 设备类型改变事件 */
        const equTypeChange = (val: any) => {
            equFun(val);
        }

        /*** 获取设备数据 */
        const equFun = async (id: number) => {
            let param: any = {};
            param.N_TypeId = id;
            let res: any = await EquipmentGetList(param);
            if(res.success) equOption.value = res.data;
        }

        /*** 获取设备类型数据 */
        const facilityTypeFun = async() => { 
            let param: any = {};
            param.n_Type = 2;
            let res: any = await ClassifyGetList(param);
            if(res.success) equTypeOption.value = res.data;
        }

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            postOption,
            postChange,
            typeOption,
            genreChange,
            genreOption: [
                {label: '天', value: 0},
                {label: '周', value: 1},
                {label: '月', value: 2},
                {label: '季', value: 3},
                {label: '年', value: 4},
            ],
            currentType,
            equTypeOption,
            equOption,
            equTypeChange,
            equChange,
        }
    },
} )
</script>
<style scoped lang="scss">
:deep(.el-cascader){
    width: 100%;
}
:deep(.el-select){
    width: 100%!important;
}
:deep(.el-input){
    width: 100%;
}
</style>